﻿using ImageDomain.DE;
using OpenCvSharp;
using ImageDomain.Utils;

namespace ImageDomain.Services;
public static class ImageSliceService
{
    public static Mat? GetAxSlice(this IImage3d? image3d, int index, bool isMask=false)
    {
        if (image3d == null || image3d.ItkImage == null) return null;
        var image = ImageHandler.Instance.GetAxSliceImage(image3d.ItkImage
            , index, image3d.OriginSize!);

        if(image == null) return null;
        return isMask ? ImageHandler.Instance.GetMatWithInt8(image, image3d.WinAdjust) 
            : ImageHandler.Instance.GetMatWithInt32(image, image3d.WinAdjust);
    }

    public static Mat? GetSagSlice(this IImage3d? image3d, int index, bool isMask=false)
    {
        if (image3d == null || image3d.ItkImage == null) return null;
        var image = ImageHandler.Instance.GetSagSliceImage(image3d.ItkImage
            , index, image3d.OriginSize!);

        if (image == null) return null;

        var sagMat = isMask ? ImageHandler.Instance.GetMatWithInt8(image, image3d.WinAdjust) 
            : ImageHandler.Instance.GetMatWithInt32(image, image3d.WinAdjust);

        if (image3d.ImageFactor == 1) return sagMat;

        var dst = new Mat(new Size(sagMat.Width, (int)sagMat.Height * image3d.ImageFactor), isMask? MatType.CV_8UC1 : MatType.CV_8UC4);
        if (isMask)
        {
            return sagMat;
            
        }
        else
        {
            Cv2.Resize(sagMat, dst, new Size(sagMat.Width, (int)sagMat.Height * image3d.ImageFactor));
        }
        sagMat = dst;
        return sagMat;
    }

    public static Mat? GetCorSlice(this IImage3d? image3d, int index, bool isMask = false)
    {
        if (image3d == null || image3d.ItkImage == null) return null;
        var image = ImageHandler.Instance.GetCorSliceImage(image3d.ItkImage
            , index, image3d.OriginSize!);

        if (image == null) return null;

        var corMat = isMask ? ImageHandler.Instance.GetMatWithInt8(image, image3d.WinAdjust) 
            : ImageHandler.Instance.GetMatWithInt32(image, image3d.WinAdjust);

        if (image3d.ImageFactor == 1) return corMat;

        var dst = new Mat(new Size(corMat.Width, (int)corMat.Height * image3d.ImageFactor), isMask ? MatType.CV_8UC1 : MatType.CV_8UC4);
        if (isMask)
        {
            return corMat;
            //Cv2.Resize(corMat, dst, new Size(corMat.Width, (int)corMat.Height * image3d.ImageFactor)
            //    , 0, 0, InterpolationFlags.Nearest);
        }
        else
        {
            Cv2.Resize(corMat, dst, new Size(corMat.Width, (int)corMat.Height * image3d.ImageFactor));
        }

        corMat = dst;
        return corMat;
    }

}
